# users/serializers.py
from rest_framework import serializers
from .models import User
import hashlib

from .utils import hash_password


def md5_encrypt(password):
    return hashlib.md5(password.encode('utf-8')).hexdigest()


class RegisterSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ['username', 'password', 'confirm_password']
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate(self, data):
        if data['password'] != data['confirm_password']:
            raise serializers.ValidationError("两次输入的密码不一致")
        return data

    def create(self, validated_data):
        validated_data.pop('confirm_password')
        validated_data['password'] = md5_encrypt(validated_data['password'])  # MD5加密
        return User.objects.create(**validated_data)


class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)

    def validate(self, data):
        username = data.get('username')
        password = data.get('password')

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise serializers.ValidationError("账号不存在")

        hashed_input = hash_password(password)
        if hashed_input != user.password:
            raise serializers.ValidationError("密码错误")

        data['user'] = user
        return data


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'user_id', 'username', 'real_name', 'phone', 'email',
            'role', 'gender', 'status', 'created_at', 'updated_at'
        ]
